package pa1.chat.client;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Calendar;
import java.util.Scanner;

import pa1.chat.server.ChatServer;


public class ChatClientImpl extends UnicastRemoteObject implements ChatClient{
	private String name;
	public static final String HOSTNAME = "127.0.0.1";
	
	protected ChatClientImpl(String name) throws RemoteException {
		super();
		this.name = name;
	}

	@Override
	public void displayMessage(String message) throws RemoteException {
		String time = Calendar.getInstance().getTime().toString();
		System.out.println("[" + time + "]" + message);
		
	}

	@Override
	public String getName() throws RemoteException {
		return this.name;
	}
	
	public static void main(String args[]){
		boolean run = true;
		Scanner input = new Scanner(System.in);
		//get client name
		String clientName;
		System.out.println("Welcome, please enter your name:");
		clientName = input.nextLine();
		
		try {
			//create a client object
			ChatClient chatClient = new ChatClientImpl(clientName);
			
			//get the server remote object
			ChatServer chatServer = (ChatServer) Naming.lookup("//" + HOSTNAME + "/" + ChatServer.SERVICE_NAME);
			
			chatServer.register(chatClient);
			
			System.out.println("You are now connected. Type --exit-- to leave the chat.");
			
			while(run){
				String message = input.nextLine();
				if(message.equalsIgnoreCase("--exit--")){
					chatServer.unregister(chatClient);
					run = false;
				}
				else{
					chatServer.sendMessage(chatClient, message);
				}
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NotBoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
